<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\model\RoleModel;
use app\admin\model\UserModel;
use app\admin\model\UserInfoModel;
use app\admin\model\AreaModel;
use app\admin\model\CompanyModel;
use app\admin\model\CouponModel;
use app\admin\model\CouponTypeModel;
use think\Db;
use think\Exception;
use org\BaiduMap;

class Coupon extends Base
{
    //用户列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                // $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $id = session('id');
            $user = new UserModel();
            $company = new CompanyModel();
            $coupon = new CouponModel();
            if(session('role_id') == 3){
                $user_type = $company->getUserType($id);
                $where['cid'] = $user_type->aid;
            }else{
                $where['cid'] = ['gt',0];
            }
            $selectResult = $coupon->getCouponByWhere($where, $offset, $limit);
            $AlreadyReceive = $coupon->getReceivePhone();

            // 拼装参数
            foreach($selectResult as &$vo){
                if($vo['expirationType'] == 1){
                    $vo['showExpirationValue'] = date('Y-m-d H:i:s',$vo['expirationValue']);
                }else{
                    $vo['showExpirationValue'] = date('Y-m-d H:i:s',($vo['receive_at']+$vo['expirationValue']*24*60*60));
                }
                if($vo['receive_at']){
                    $vo['showExpirationValue'] = $vo['showExpirationValue'];
                }else{
                    $vo['showExpirationValue'] = '-';
                }
                if(array_key_exists($vo['uid'],$AlreadyReceive)){
                    $vo['phone'] = $AlreadyReceive[$vo['uid']];
                        }else{
                    $vo['phone'] = '-';
                        }
                switch ($vo['status']) {
                    case 1 :
                        $vo['show_status_time'] = $vo['showExpirationValue'];
                        break;
                    case 2 :
                        $vo['show_receive_time'] = date('Y-m-d H:i:s',$vo['receive_at']);
                        break;
                    case 3 :
                        $vo['show_use_time'] = $vo['use_at'];
                        break;
                }
                $vo['operate'] = showOperate($this->makeButton($vo['id'],$vo['status']));
            }
            unset($key);
            unset($vo);

            $return['total'] = $coupon->getAllCoupon($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }
        $user_id = session('id');
        $role_id = session('role_id');
        $role = new RoleModel();
        $AreaModel = new AreaModel();
        $CompanyModel = new CompanyModel();
        $this->assign([
            // 'role' => $role->getPartRole(),
            'company' => $CompanyModel->getTopCompany($user_id,$role_id),
            'coupon' => config('Coupon'),
        ]);
        return $this->fetch();
    }

    /**
     * [indexAdd 给用户添加红包]
     * @return [type] [description]
     */
    public function indexSend()
    {
        if(request()->isPost()){
            $param = input('post.');
            $company = new CompanyModel();
            $user = new UserModel();
            $couponType = new CouponTypeModel();
            $coupon = new CouponModel();
            $param['cid'] = $param['company'];
            $param['create_at'] = time();
            $param['update_at'] = time();
            $wxUser = new UserInfoModel();
            $phones = explode(',',$param['phone']);

            Db::startTrans();
                try{
                    $wxUserInfo = $wxUser->getUserData($phones);
                    $countCoupon = $company->getAllCouponInfo($param['cid']);
                        if(count($countCoupon['rows']) < count($wxUserInfo)*$param['number']){
                            return json(msg('-1', '', '优惠券不足'));
                        }
                        $c = [];
                        $res = false;
                        if(count($wxUserInfo) < 2){
                            // $c[] = array_fill_keys($countCoupon['bid'],);
                                
                                foreach ($countCoupon['bid'] as $key => $value) {
                                    $couponData = [];
                                    $couponData['expiration'] = time()+366*24*60*60;;
                                    $couponData['receive_at'] = time();
                                    $couponData['updated_at'] = time();
                                    $couponData['status'] = 2;
                                    $couponData['uid'] = $wxUserInfo[0];
                                    $res = $coupon->saveData($couponData,$value);
                                }
                        }else{
                            $newCoupon = array_chunk($countCoupon['bid'],$param['number']);
                            foreach ($newCoupon as $key => $value) {
                                $c[]= array_flip(array_combine($value,$wxUserInfo));
                            }
                            $insert_arr = [];
                            $couponData = [];
                            foreach ($c as $key => $value) {
                                foreach ($value as $k => $val) {
                                    $couponData['expiration'] = time()+366*24*60*60;;
                                    $couponData['receive_at'] = time();
                                    $couponData['updated_at'] = time();
                                    $couponData['status'] = 2;
                                    $couponData['uid'] = $k;
                                    $res = $coupon->saveData($couponData,$val);
                                }
                            }
                        }


                    // 提交事务
                    if($res){
                        Db::commit();
                        return json(msg(1, url('coupon/index'), '添加优惠券成功'));
                    }else{
                        throw new Exception("Error");
                    }
                } catch (\PDOException $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(msg('-1', '', $e->getMessage()));
                }
        }
    }

        //用户列表
    public function coupontype()
    {
        $id = session('id');
        if(request()->isAjax()){

            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                // $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $id = session('id');
            $user = new UserModel();
            $company = new CompanyModel();
            $couponType = new CouponTypeModel();

            if(session('role_id') == 3){
                $user_type = $company->getUserType($id);
                $where['a.cid'] = $user_type->aid;
            }else{
                $where['a.cid'] = ['gt',0];
            }
            $where['a.status'] = 1;
            $selectResult = $couponType->getCouponTypeByWhere($where, $offset, $limit);

            // 拼装参数
            foreach($selectResult as $key=>$vo){
                // $selectResult[$key]['last_login_time'] = date('Y-m-d H:i:s', $vo['last_login_time']);
                // $selectResult[$key]['showstatus'] = $status[$vo['status']];
                if($vo['expirationType'] == 1){
                    $selectResult[$key]['showExpirationValue'] = date('Y-m-d',$vo['expirationValue']);
                }else{
                    $selectResult[$key]['showExpirationValue'] = $vo['expirationValue'];
                }
                // 1未领取 2已领取 3已使用
                $selectResult[$key]['noReceive'] = $vo['cnumber1'];
                $selectResult[$key]['yesReceive'] = $vo['cnumber2'];
                $selectResult[$key]['use'] = $vo['cnumber3'];

                // $selectResult[$key]['showlevel'] = $level[$vo['level']];

                // if( 1 == $vo['id'] ){
                //     $selectResult[$key]['operate'] = '';
                //     continue;
                // }
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id'],$vo['status']));
            }

            $return['total'] = $couponType->getAllCouponType($where);  //总数据
            $return['rows'] = $selectResult;
            return json($return);
        }
        $user_id = session('id');
        $role_id = session('role_id');
        $role = new RoleModel();
        $AreaModel = new AreaModel();
        $CompanyModel = new CompanyModel();
        $this->assign([
            // 'role' => $role->getPartRole(),
            'company' => $CompanyModel->getTopCompany($user_id,$role_id),
            'coupon' => config('Coupon'),
        ]);
        return $this->fetch();
    }

    // 添加优惠券
    public function addCoupon()
    {
        if (IS_POST) {
            $data = I('post.');
            $CouponTypeInfo = $this->CouponTypeModel->find($data['typeId']);
            if ($CouponTypeInfo['expirationType'] == 1) {
                $expiration = strtotime($CouponTypeInfo['expirationValue']);
            } else {
                $expiration = '';
            }
            
            $msg = doReturn("生成成功", "生成失败", $res);
            $this->ajaxReturn($msg);
        }
        $this->display();
    }

    // 添加用户
    public function couponAdd()
    {
        if(request()->isPost()){

            $param = input('post.');
            $company = new CompanyModel();
            $user = new UserModel();
            $couponType = new CouponTypeModel();
            $coupon = new CouponModel();

            if($param['expirationType'] == 1 ){
                $param['expirationValue'] = strtotime($param['expirationValue']);
            }
            $param['cid'] = $param['company'];
            $param['create_at'] = time();
            $param['update_at'] = time();
            dump($param);
            Db::startTrans();
                try{
                    if($couponType->validate('CouponTypeValidate.addData')->save($param)){
                        $insert_arr = [];
                            for ($i = 0; $i < $param['number']; $i++) {
                                $couponData['uid'] = 0;
                                $couponData['code'] = strtoupper(md5(microtime(true) . $i . randString($i)));;
                                $couponData['status'] = 1;
                                $couponData['type'] = $couponType->id;
                                $couponData['expiration'] = 0;
                                $couponData['receive_at'] = 0;
                                $couponData['use_at'] = 0;
                                $couponData['created_at'] = time();
                                $couponData['updated_at'] = time();
                                $insert_arr[] = $couponData;
                            }

                        $res = $coupon->saveAll($insert_arr,false);

                    }else{
                        throw new Exception("Error");
                    }
                    // 提交事务
                    if($res){
                        Db::commit();
                        return msg(1, url('coupon/coupontype'), '添加优惠券成功');
                    }else{
                        throw new Exception("Error");
                        
                    }
                } catch (\PDOException $e) {
                    // 回滚事务
                    Db::rollback();
                    return msg('-1', '', $e->getMessage());
                }
        }
    }

    // 编辑用户
    public function userEdit()
    {
        $company = new CompanyModel();
        // if(request()->isPost()){

            $param = input('param.');
            $flag = $company->editUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        // }

        // $id = input('param.id');
        // $role = new RoleModel();
        // $this->assign([
        //     'user' => $company->getOneUser($id),
        //     'status' => config('user_status'),
        //     // 'role' => $role->getRole()
        // ]);
        // $this->assign([
        //     'user' => $company->getOneUser($id),
        //     'status' => config('user_status'),
        //     'role' => $role->getRole()
        // ]);
        // return $this->fetch();
    }

    // 删除用户
    // public function userDel()
    // {
    //     $id = input('param.id');

    //     $company = new CompanyModel();
    //     $flag = $company->delUser($id);
    //     return json(msg($flag['code'], $flag['data'], $flag['msg']));
    // }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id,$status)
    {
        if($status == 1){
            return [
                '禁用' => [
                    'auth' => 'company/useredit',
                    // 'href' => url('company/userEdit', ['id' => $id]),
                    'href' => "javascript:userEdit(" .$id .','.$status.")",
                    'btnStyle' => 'primary',
                    'icon' => 'fa fa-paste'
                ],
                // '删除' => [
                //     'auth' => 'user/userdel',
                //     'href' => "javascript:userDel(" .$id .")",
                //     'btnStyle' => 'danger',
                //     'icon' => 'fa fa-trash-o'
                // ]
            ];
        }else{
            return [
                '启用' => [
                    'auth' => 'company/useredit',
                    // 'href' => url('company/userEdit', ['id' => $id]),
                    'href' => "javascript:userEdit(" .$id .','.$status.")",
                    'btnStyle' => 'primary',
                    'icon' => 'fa fa-paste'
                ],
                // '删除' => [
                //     'auth' => 'user/userdel',
                //     'href' => "javascript:userDel(" .$id .")",
                //     'btnStyle' => 'danger',
                //     'icon' => 'fa fa-trash-o'
                // ]
            ];
        }
    }
}
